package m.store.service;

import m.base.util.PowerUtil;
import m.common.model.util.*;
import m.common.service.Service;
import m.store.model.*;
import m.system.exception.MException;
import m.system.util.DateUtil;
import m.system.util.GenerateID;
import m.system.util.NumberUtil;
import m.system.util.ObjectUtil;

import java.sql.SQLException;
import java.util.Date;
import java.util.List;

public class GuestBackAmountService extends Service {
    public String save(GuestBackAmount model) throws Exception {
        ModelQueryCheck.init(model)
            .checkNotNull("linkStatus","状态错误")
            .checkStrEq("linkStatus", GuestBackAmount.LinkStatus_No,"未关联才能修改")
            .checkNotNull("guest.oid","请选择收款客户")
            .checkNotNull("type","类型错误")
            .checkNotNull("business","请选择主营业务")
            .checkNotNull("mode","请选择支付方式")
            .checkNotNull("backAmount","请输入支付金额")
            .checkNumberRange("backAmount",0.01,9999999999D,"支付金额至少是0.01")
            .checkNotNull("backDate","请选择支付时间")
            .doCheck(false,true);
        PowerUtil.verifyAccountDate(model.getBackDate(),"支付时间");
        String msg="";
        if(ObjectUtil.isEmptyOid(model)){
            model.setOid(GenerateID.generatePrimaryKey());
            ModelUpdateUtil.insertModel(model);
            msg="保存成功";
        }else{
            ModelUpdateUtil.updateModel(model,"guest.oid","business","mode","backAmount","backDate","remark");
            msg="修改成功";
        }
        return msg;
    }
    /**
     * 删除
     */
    public void delete(String oid) throws Exception {
        GuestBackAmount model=ModelQueryList.getModel(GuestBackAmount.class,oid,"*");
        PowerUtil.verifyStoreData(model.getStore().getOid());
        ModelQueryCheck.init(model)
            .checkStrEq("linkStatus",GuestBackAmount.LinkStatus_No,"未关联才能删除")
            .doCheck(false,true);
        ModelUpdateUtil.deleteModel(model);
    }
    public void split(String oid) throws Exception {
        GuestBackAmount model=ModelQueryList.getModel(GuestBackAmount.class,oid,"*");
        PowerUtil.verifyStoreData(model.getStore().getOid());
        ModelQueryCheck.init(model)
            .checkStrEq("linkStatus",GuestBackAmount.LinkStatus_linking,"部分关联的才能拆分")
            .doCheck(false,true);
        double newAmount=NumberUtil.round(model.getBackAmount()-model.getLinkAmount(),2);
        model.setBackAmount(model.getLinkAmount());
        ModelUpdateUtil.updateModel(model,"backAmount");
        updateLinkAmount(model.getOid());
        model.setOid(GenerateID.generatePrimaryKey());
        model.setBackAmount(newAmount);
        model.setLinkAmount(0d);
        model.setLinkStatus(GuestBackAmount.LinkStatus_No);
        ModelUpdateUtil.insertModel(model);
    }

    private void updateLinkAmount(String oid) throws MException {
        ModelUpdate.init(GuestBackAmount.class)
            .set("linkAmount",GuestAmountLink.class,"round(ifnull(sum(#{linkAmount}),0),2)",
                QueryCondition.eq("backAmount.oid",oid))
            .setExp("linkStatus","if(#{linkAmount}>0,if(#{linkAmount}=#{backAmount},'Y','A'),'N')")
            .execute(oid);
    }

    /**
     * 关联付款金额  付款订单审核调用
     */
    public void linkAmount(PayAmount pay) throws SQLException, MException {
        if(pay.getPayAmount()>0){
            linkAmount(GuestBackAmount.Type_Pay,"付款", pay.getPayAmount(), pay.getPayDate(),pay);
        }else{
            linkAmount(GuestBackAmount.Type_Income,"收款", -pay.getPayAmount(), pay.getPayDate(),pay);
        }
    }

    /**
     * 关联收款金额  收款订单审核调用
     */
    public void linkAmount(IncomeAmount income) throws SQLException, MException {
        if(income.getIncomeAmount()>0) {
            linkAmount(GuestBackAmount.Type_Income, "收款", income.getIncomeAmount(), income.getIncomeDate(), income);
        }else{
            linkAmount(GuestBackAmount.Type_Pay, "付款", -income.getIncomeAmount(), income.getIncomeDate(), income);
        }
    }
    private void linkAmount(String type,String typeName, Double money, Date date, OrderModel order) throws SQLException, MException {
        List<GuestBackAmount> ls=ModelQueryList.getModelList(GuestBackAmount.class,new String[]{"*"},null,
            QueryCondition.and(
                QueryCondition.eq("guest.oid",order.getGuest().getOid()),
                QueryCondition.eq("type",type),
                QueryCondition.eq("business",GuestBackAmount.Business_Yes),
                QueryCondition.ge("backDate", DateUtil.getStartDay(date)),
                QueryCondition.le("backDate", DateUtil.getEndDay(date))
            )
        );
        Double all=money;
        for(GuestBackAmount amount : ls){
            GuestAmountLink link=new GuestAmountLink();
            link.setOid(GenerateID.generatePrimaryKey());
            link.setBackAmount(amount);
            if(order instanceof PayAmount) link.setPay((PayAmount) order);
            if(order instanceof IncomeAmount) link.setIncome((IncomeAmount) order);
            Double other= NumberUtil.round(amount.getBackAmount()-amount.getLinkAmount(),2);
            if(other>=all){
                link.setLinkAmount(all);
                ModelUpdateUtil.insertModel(link);
                updateLinkAmount(amount.getOid());
                return;
            }else{
                link.setLinkAmount(other);
                ModelUpdateUtil.insertModel(link);
                updateLinkAmount(amount.getOid());
                all=NumberUtil.round(all-other,2);
            }
        }
        if(all>0) throw new MException(this.getClass(),"客户"+DateUtil.format(date,DateUtil.YYYY_MM_DD)+"的"+typeName+"不足，请先登记客户"+typeName+"信息。");
    }
}
